import {
    DetailResult,
    EcgData,
    QRSAnaResponse,
    RawEcgParam,
    Study,
    type EcgXWave,
    type VerticalLine,
} from '@/pages/types/type';
import { postRequestInit, urlPrefix } from '@/utils/http';
import {
    Button,
    Checkbox,
    Picker,
    Popup,
    Radio,
    Space,
    Tag,
    Toast,
} from 'antd-mobile';
import { ToastHandler } from 'antd-mobile/es/components/toast';
import React, {
    Dispatch,
    SetStateAction,
    useEffect,
    useRef,
    useState,
    useCallback
} from 'react';
import styles from './index.less';
interface XY {
    clientX: number;
    clientY: number;
}
interface OffsetXY {
    offsetX: number;
    offsetY: number;
}
interface WH {
    width: number;
    height: number;
}
/*
 // Firefox兼容方案
  const offsetX = event.offsetX || 
                 (event.clientX - event.target.getBoundingClientRect().left);*/
export default () => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    // 产生一个随机的颜色
    function gc() {
        var s = "0123456789ABCDEF";
        var c = "#";
        for (var i = 0; i < 6; i++) {
            c += s[Math.ceil(Math.random() * 15)];
        }
        return c;
    }

    // 假设鼠标初始位置
    const [mouseXYOnWindow, setMouseXYOnWindow] = useState<XY>({ clientX: innerWidth / 2, clientY: innerHeight / 2 });
    const [mouseXYOnCanvas, setMouseXYOnCanvas] = useState<OffsetXY>()
    // 调整度
    const [winWH, setWH] = useState<WH>({ width: innerWidth, height: innerHeight });

    // 使用useCallback保持函数引用稳定
    const handleMouseMoveOnWindow = useCallback((event: MouseEvent) => {
        const { clientX, clientY } = event;
        setMouseXYOnWindow({ clientX, clientY });
        // console.log('Mouse position:', event.clientX, event.clientY);
    }, []);

    // useEffect(() => {
    //     // 添加监听，泛型参数为"mousemove"
    //     window.addEventListener<"mousemove">("mousemove", handleMouseMoveOnWindow);
    //     return () => {
    //         // 移除时需保持相同类型和引用
    //         window.removeEventListener<"mousemove">("mousemove", handleMouseMoveOnWindow);
    //     };
    // }, [handleMouseMoveOnWindow]);

    // canvas 的mouse move事件
    const handleMouseMoveOnCanvas = useCallback((event: MouseEvent) => {
        const { offsetX, offsetY } = event;
        setMouseXYOnCanvas({ offsetX, offsetY })
        console.log('handleMouseMoveOnCanvas:', event.offsetX, event.offsetY, window.devicePixelRatio);
    }, []);

    useEffect(() => {
        const canvas = canvasRef.current;
        const ctx = canvas?.getContext('2d');
        if (ctx && canvas) {
            // 添加监听，泛型参数为"mousemove"
            canvas.addEventListener<"mousemove">("mousemove", handleMouseMoveOnCanvas);
            return () => {
                // 移除时需保持相同类型和引用
                canvas.removeEventListener<"mousemove">("mousemove", handleMouseMoveOnCanvas);
            };
        }
    }, [handleMouseMoveOnCanvas]);

    const handleResize = useCallback((event: UIEvent) => {
        const { innerWidth, innerHeight } = window;
        setWH({
            width: innerWidth,
            height: innerHeight,
        });
        console.log('handleResize:', event);
    }, [])

    useEffect(() => {
        // 添加监听，泛型参数为"mousemove"
        window.addEventListener<"resize">("resize", handleResize);
        return () => {
            // 移除时需保持相同类型和引用
            window.removeEventListener<"resize">("resize", handleResize);
        };
    }, [handleResize]);

    useEffect(() => {
        const canvas = canvasRef.current;
        const ctx = canvas?.getContext('2d');
        if (ctx && canvas) {
            const { width, height } = winWH;

            const devicePixelRatio = window.devicePixelRatio || 1;
            const displayWidth = width - 20;
            const displayHeight = height * 0.3;

            // 设置canvas的实际像素尺寸
            canvas.width = displayWidth * devicePixelRatio;
            canvas.height = displayHeight * devicePixelRatio;

            // 设置canvas的显示尺寸
            canvas.style.width = displayWidth + 'px';
            canvas.style.height = displayHeight + 'px';

            // 缩放绘图上下文以匹配设备像素比
            ctx.scale(devicePixelRatio, devicePixelRatio);

            // 优化渲染质量，提高清晰度
            ctx.imageSmoothingEnabled = false;
            ctx.textRendering = 'optimizeSpeed';
        } //end if  ctx && canvas
    }, [winWH]);

    useEffect(() => {
        const canvas = canvasRef.current;
        const ctx = canvas?.getContext('2d');
        if (ctx && canvas) {

            ctx.clearRect(0, 0, winWH.width, winWH.height);
            const { offsetX, offsetY } = mouseXYOnCanvas || {};
            const hx = offsetX !== undefined && offsetY !== undefined ;
            for (let i = 0; i < 6; i++) {
                for (let j = 0; j < 6; j++) {
                    var xRect = new Path2D();

                    xRect.rect(j * 25, i * 25, 25, 25);

                    var hh = hx? (ctx.isPointInPath(xRect, offsetX * devicePixelRatio, offsetY * devicePixelRatio) ? '0.2' : '1') : '1';

                    ctx.fillStyle = `rgba(${Math.floor(255 - 42.5 * i)},${Math.floor(255 - 42.5 * j,)},0,${hh})`;
                    ctx.fill(xRect);
                }
            }

            const circle = new Path2D();
            circle.arc(200, 100, 50, 0, 2 * Math.PI);
            ctx.fillStyle = hx? (ctx.isPointInPath(circle, offsetX * devicePixelRatio, offsetY * devicePixelRatio)? "green":'red'):'red';
            ctx.fill(circle);

        }
    }, [mouseXYOnWindow, mouseXYOnCanvas])

    return (
        <div className={styles.container}>
            {/* Canvas */}
            <div className={styles.canvasArea}>
                <canvas
                    ref={canvasRef}
                    className={styles.canvas}
                // onMouseDown={handlePointerDown}
                // onMouseMove={handlePointerMove}
                // onMouseUp={handlePointerUp}
                // onMouseLeave={handlePointerLeave}
                // onTouchStart={handlePointerDown}
                // onTouchMove={handlePointerMove}
                // onTouchEnd={handlePointerUp}
                ></canvas>
            </div>
            abs
        </div>
    );
}